<template>
  <div ref="chart" style=" height: 300px"></div>
</template>
<script>
import http from "@/api/http";
import * as echarts from "echarts/core";
export default {
  data() {
    return {
      chart: null,
      chartData: [],
    };
  },
  methods: {
    async initChart() {
      // 确保 DOM 元素存在
      if (!this.$refs.chart) {
        console.error("Chart container is not found.");
        return;
      }

      this.chart = echarts.init(this.$refs.chart);
      // window.addEventListener("resize", function () {
      //   this.chart.resize();
      // });
      console.log(this.chart);

      try {
        const response = await http.get("/baoxiu/repaire_type");
        this.chartData = response.data;
        console.log(response.data);

        this.chart.setOption({
          title: {
            text: '报修类型',
            // subtext: 'Fake Data',
            left: 'center'
          },
          tooltip: {
            trigger: 'item',
            formatter: "{a} <br/>{b} : {c} ({d}%)"
          },
          legend: {
            orient: 'vertical',
            left: 'left'
          },
          series: [
            {
              name: "维修数据",
              type: "pie",
              radius: "50%",
              data: [
                { value: this.chartData[0], name: "自然损坏" },
                { value: this.chartData[1], name: "人为损坏" },
              ],
            },
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
          label: {
            show: true, // 显示标签
            position: "top", // 标签的位置
            formatter: "{c}", // 标签的内容，{c} 表示系列数据的数值
          },
        });
      } catch (error) {
        console.error("获取数据失败:", error);
      }
    },
  },
  mounted() {
    // 调用方法
    this.initChart();
  },
};
</script>